/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BANewsEventsViewController_iPad.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 10/15/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BANewsEventsViewController_iPad.h"
#import "BAFlyoutMenuViewController.h"
#import "BALibrarySettings.h"
#import "UIImage+MultiplyColor.h"
#import "BAPopularItemsViewController.h"
#import "BATabSwitchViewController.h"
#import "BANewsTableViewController.h"
#import "BAEventsTableViewController.h"
#import "BAPopular.h"
#import "BARootViewController.h"
#import "BAColoredCoverViewController.h"

#ifdef BA_IMF_BUILD
#import "IMFSuggestedPackagePageViewController.h"
#import "IMFRPCManager.h"
#endif

@class IMFSuggestedPackagePageViewController;

@interface BANewsEventsViewController_iPad (){
    BAColoredCoverViewController* coloredCoverLoadingIndicator;
    BOOL suggestedPackagesLoaded;
    BOOL newsLoaded;
    BOOL eventsLoaded;
    BOOL popularLoaded;
}

@property (strong, nonatomic) BANewsTableViewController* newsViewController;
@property (nonatomic, strong) BAEventsTableViewController* eventsViewController;
@property (weak, nonatomic) IBOutlet UIView *newsContainerView;
@property (weak, nonatomic) IBOutlet UIView *eventsContainerView;


@property (strong, nonatomic) BAPopularItemsViewController* section2ViewController;
@property (weak, nonatomic) IBOutlet UIView *section2ContainerView;
@property (weak, nonatomic) IBOutlet UIView *section2HeaderBackgroundView;
@property (weak, nonatomic) IBOutlet UILabel *section2HeaderTitle;
@property (weak, nonatomic) IBOutlet UIImageView *section2HeaderImageView;

@property (strong, nonatomic) BAPopularItemsViewController* section3ViewController;
@property (weak, nonatomic) IBOutlet UIView *section3ContainerView;
@property (weak, nonatomic) IBOutlet UIView *section3HeaderBackgroundView;
@property (weak, nonatomic) IBOutlet UILabel *section3HeaderTitle;
@property (weak, nonatomic) IBOutlet UIImageView *section3HeaderImageView;

@property (weak, nonatomic) IBOutlet UIView *tabSwitchView;

@property (strong, nonatomic) NSDate* lastLoadedNewsDate;
@property (strong, nonatomic) NSDate* lastLoadedArrangementsDate;
@property (strong, nonatomic) NSDate* lastLoadedPopularDate;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topRightContainerHeight;
@property (weak, nonatomic) IBOutlet UIView *topRightSearchContainerView;
@property (weak, nonatomic) IBOutlet UIView *topRightIMFContainerView;

@property (strong, nonatomic) IMFSuggestedPackagePageViewController *suggestedPackagePager;


@end

@implementation BANewsEventsViewController_iPad

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationDefault)
    [self.view setBackgroundColor:[[BALibrarySettings instance] getCustomerColorNormal]];
    
    [self.section2HeaderBackgroundView setBackgroundColor:[[BALibrarySettings instance] getCustomerColorDark]];
    [self.section3HeaderBackgroundView setBackgroundColor:[[BALibrarySettings instance] getCustomerColorDark]];
    
    BA_LABEL_SET_FONT_MEDIUM(self.section2HeaderTitle);
    BA_LABEL_SET_FONT_MEDIUM(self.section3HeaderTitle);
    
    
    _newsViewController = [BANewsTableViewController new];
    [self.newsContainerView addSubview:self.newsViewController.view];
    [self addChildViewController:self.newsViewController];
    [self setViewToFillParent:self.newsViewController.view];
    
    _eventsViewController = [BAEventsTableViewController new];
    [self.eventsContainerView addSubview:self.eventsViewController.view];
    [self addChildViewController:self.eventsViewController];
    [self setViewToFillParent:self.eventsViewController.view];
    
    //dep: [self.section2HeaderImageView setImage:[UIImage imageNamed:@"popular-audio-Icon" multiplyWithColor:[[BALibrarySettings instance] getCustomerColorDark]]];
    //dep: [self.section3HeaderImageView setImage:[UIImage imageNamed:@"popular-book-Icon" multiplyWithColor:[[BALibrarySettings instance] getCustomerColorDark]]];
    
    _section2ViewController = [BAPopularItemsViewController new];
    [self.section2ContainerView addSubview:self.section2ViewController.view];
    [self addChildViewController:self.section2ViewController];
    [self setViewToFillParent:self.section2ViewController.view];
    
    _section3ViewController = [BAPopularItemsViewController new];
    [self.section3ContainerView addSubview:self.section3ViewController.view];
    [self addChildViewController:self.section3ViewController];
    [self setViewToFillParent:self.section3ViewController.view];
    
    
    BATabSwitchViewController* tabswitch = [[BATabSwitchViewController alloc] initWithSelectionColor:nil unselectionColor:[UIColor colorWithWhite:0.85 alpha:1]];
    [self.tabSwitchView addSubview:tabswitch.view];
    [self setViewToFillParent:tabswitch.view];
    //[tabswitch.view setFrame:self.tabSwitchView.bounds];
    
    [tabswitch setTitleStrings:@[@"NYHEDER",@"ARRANGEMENTER"]];
    [self addChildViewController:tabswitch];
    [tabswitch setDelegate:self];
    
    coloredCoverLoadingIndicator = [BAColoredCoverViewController new];
    [self.navigationController.view addSubview:coloredCoverLoadingIndicator.view];
    [BAUtils setViewToFillParent:coloredCoverLoadingIndicator.view];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receivedDidBecomeActiveNotification:)
                                                 name:BA_APP_DELEGATE_DID_BECOME_ACTIVE
                                               object:nil];
    
    [self loadPopular];
    [self updateNewsAndArrangementsLists];

    if ([BALibrarySettings instance].isImfEnabled) {
        [self updateSuggestedPackages];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self enableUserInteraction];
    [self updateNewsArrangementsPopularsIfNeeded];
}

-(void)dealloc
{
    [BARPCManager closeConnectionsForView:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_APP_DELEGATE_DID_BECOME_ACTIVE object:nil];
}

-(void)updateSuggestedPackages
{
#ifdef BA_IMF_BUILD
    [IMFRPCManager getSuggestedPackagesAsyncFromView:self
                                               count:4
                                      skipPackageIds:@[]
                                              result:^(NSArray* result) {
                                                  if (result.count > 0) {
                                                      [self.topRightSearchContainerView setHidden:YES];
                                                      [self.topRightIMFContainerView setHidden:NO];
                                                      self.topRightContainerHeight.constant = 226;
//                                                      [self.topFeatureLoadingIndicator stopAnimating];
                                                      
                                                      if (self.suggestedPackagePager==nil) {
                                                          _suggestedPackagePager = [IMFSuggestedPackagePageViewController new];
//                                                          [self.suggestedPackagePager.view setFrame:self.topRightIMFContainerView.bounds];
                                                          [self.topRightIMFContainerView addSubview:self.suggestedPackagePager.view];
                                                          [BAUtils setViewToFillParent:self.suggestedPackagePager.view];
                                                          [self addChildViewController:self.suggestedPackagePager];
                                                      }
                                                      [self.suggestedPackagePager setPackages:result];
                                                  }
                                                  suggestedPackagesLoaded = YES;
                                                  [self dismissColoredCover];
                                                  
                                              } errorBlock:^(int errorCode, NSString *errorMessage) {
                                                  DLog(@"ERROR getSuggestedPackagesAsyncFromView: %@",errorMessage);
                                                  suggestedPackagesLoaded = YES;
                                                  [self dismissColoredCover];
                                                  //TODO
                                              }
     ];
#endif
}

- (void) receivedDidBecomeActiveNotification:(NSNotification*) notification
{
    [self updateNewsArrangementsPopularsIfNeeded];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}

-(void)updateNewsArrangementsPopularsIfNeeded
{
    //TODO: update packages!
    
    bool doUpdate=false;
    if (self.lastLoadedNewsDate==nil || [self.lastLoadedNewsDate timeIntervalSinceNow]<-3600) {
        doUpdate=true;
    }
    if (self.lastLoadedArrangementsDate==nil || [self.lastLoadedArrangementsDate timeIntervalSinceNow]<-3600) {
        doUpdate=true;
    }
    if (doUpdate) {
        [self updateNewsAndArrangementsLists];
    }
    
    if (self.lastLoadedPopularDate==nil || [self.lastLoadedPopularDate timeIntervalSinceNow]<-600) {
        [self.section2ViewController clearAndSetIsLoading];
        [self.section3ViewController clearAndSetIsLoading];
        [self loadPopular];
    }
}

-(void)updateNewsAndArrangementsLists
{
    self.lastLoadedNewsDate = [NSDate date]; //avoid multiple concurrent calls
    [BARPCManager loadAllNewsFromView:self
                          resultBlock:^(NSArray *results) {
                              newsLoaded = YES;
                              [self.newsViewController setNewsElements:results];
                              self.lastLoadedNewsDate = [NSDate date];
                              [self dismissColoredCover];
                          } errorBlock:^(int errorCode, NSString *errorMessage) {
                              newsLoaded = YES;
                              DLog(@"ERROR loadAllNewsFromView: %@",errorMessage);
                              [self.newsViewController setNewsElements:nil];
                              self.lastLoadedNewsDate = nil;
                              [self dismissColoredCover];
                          }];
    
    self.lastLoadedArrangementsDate = [NSDate date]; //avoid multiple concurrent calls
    [BARPCManager loadAllEventsFromView:self
                            resultBlock:^(NSArray *results) {
                                eventsLoaded = YES;
                                [self.eventsViewController setEventElements:results];
                                self.lastLoadedArrangementsDate = [NSDate date];
                            } errorBlock:^(int errorCode, NSString *errorMessage) {
                                eventsLoaded = YES;
                                DLog(@"ERROR loadAllEventsFromView: %@",errorMessage);
                                [self.eventsViewController setEventElements:nil];
                                self.lastLoadedArrangementsDate=nil;
                            }];
    
}

-(void)loadPopular{
   self.lastLoadedPopularDate = [NSDate date]; //avoid multiple concurrent calls
   [BARPCManager getPopularAsyncFromView:self
                                listCount:2
                                 listSize:10
                              resultBlock:^(NSArray *result) {
                                  if (result.count == 0) {
                                      [self.section2ViewController setPopular:nil];
                                      [self.section3ViewController setPopular:nil];

                                  } else if (result.count == 1) {
                                      BAPopular* popular1 = [result objectAtIndex:0];
                                      [self.section2ViewController setPopular:popular1];
                                      [self.section3ViewController setPopular:nil];

                                  }else{
                                      BAPopular* popular1 = [result objectAtIndex:0];
                                      [self.section2ViewController setPopular:popular1];
                                      BAPopular* popular2 = [result objectAtIndex:1];
                                      [self.section3ViewController setPopular:popular2];

                                  }
                                  self.lastLoadedPopularDate = [NSDate date];
                                  
                                  popularLoaded = YES;
                                  [self dismissColoredCover];
                              }
                               errorBlock:^(int code, NSString *error) {
                                   DLog(@"load popular error: %@",error);
                                   self.lastLoadedPopularDate=nil;
                                   [self.section2ViewController setPopular:nil];
                                   [self.section3ViewController setPopular:nil];
                                   popularLoaded = YES;
                                   [self dismissColoredCover];
                               }
     ];
}

-(void)dismissColoredCover
{
    if (coloredCoverLoadingIndicator==nil) {
        return;
    }

#ifdef BA_IMF_BUILD
    if ([BALibrarySettings instance].isImfEnabled && !suggestedPackagesLoaded) {
        return;
    }
#endif
    if (!newsLoaded) {
        return;
    }
    
    if (!popularLoaded) {
        return;
    }
    
    CGRect animframe = coloredCoverLoadingIndicator.view.frame;
    
    animframe.origin.y -= animframe.size.height;
    
    BOOL isShowingUserGuide = [BARootViewController instance].isShowingUserGuide;
    
    [UIView animateWithDuration:isShowingUserGuide ? 1.0 : 0.5
                     animations:^{
                         if (isShowingUserGuide) {
                             //if userguide present, just fade out
                             coloredCoverLoadingIndicator.view.alpha=0;
                         } else {
                             //otherwise move upwards and out
                             coloredCoverLoadingIndicator.view.frame = animframe;
                         }
                     }
                     completion:^(BOOL finished) {
                         [coloredCoverLoadingIndicator.view removeFromSuperview];
                         coloredCoverLoadingIndicator = nil;
                     }
     ];
}

#pragma mark - Helper methods;

-(void)setViewToFillParent:(UIView*)view{
    if (view.superview != nil) {
        view.translatesAutoresizingMaskIntoConstraints = NO;
        
        [view.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(view)]];
        [view.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(view)]];
    }
}

#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}


#pragma mark - BATabSwitchDelegate

-(void)tabSwitchSelected:(int)index withTitle:(NSString *)title{
    if (index == 0) {
        [self.newsContainerView setHidden:NO];
        [self.eventsContainerView setHidden:YES];
    } else{
        [self.newsContainerView setHidden:YES];
        [self.eventsContainerView setHidden:NO];
    }
}

#pragma mark - UISearchBarDelegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (searchBar.text.length > 0) {
        [searchBar resignFirstResponder];
        [[BARootViewController instance] openUserSearchViewWithSearchString:searchBar.text];
    }
}

/* old code
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length > 0) {
        [textField resignFirstResponder];
        [self.tabBarController setSelectedIndex:2]; //FIXME
        [self.searchViewController search:textField.text];
        
        return YES;
    } else{
        return NO;
    }
}
*/
@end
